﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace SPVisualDev.Services
{
    internal class AppDomainCreator<TWorker> : IDisposable
    {
        private AppDomainSetup m_domainInfo = new AppDomainSetup();
        private AppDomain m_newDomain = null;

        public AppDomainCreator()
        {
            // Create application domain setup information for new application domain.
            AssemblyName assemblyName = Assembly.GetExecutingAssembly().GetName();

            m_domainInfo.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            m_domainInfo.ApplicationName = assemblyName.Name + "_" + Guid.NewGuid().ToString("N");

            // Create appdomain.
            m_newDomain = AppDomain.CreateDomain(assemblyName.Name + "_domain_" + Guid.NewGuid().ToString("N"), null, m_domainInfo);

            // Load an assembly into the new application domain.
            this.Worker = (TWorker)m_newDomain.CreateInstanceAndUnwrap(assemblyName.FullName, typeof(TWorker).FullName);
        }

        public TWorker Worker
        {
            get;
            private set;
        }

        #region IDisposable Members

        public void  Dispose()
        {
            if (m_newDomain != null)
                AppDomain.Unload(m_newDomain);
        }

        #endregion
}
}
